package com.lg.spring.echo;

import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

/**
 * 这种递进式的 继承关系，使用的是适配器模式
 * <p>
 * 在接口中定义的都是抽象方法，并且在 默认实现中，会有大量的空实现，在具体的实例实现中，就根据具体的实现方法
 *
 * @author by Mr. Li 2020/9/12 16:52
 */
public class EchoWebSocketHandler extends TextWebSocketHandler {

	private EchoService echoService;

	public EchoWebSocketHandler(EchoService echoService) {
		this.echoService = echoService;
	}

	/**
	 * 连接建立之后
	 *
	 * @param session
	 * @throws Exception
	 */
	@Override
	public void afterConnectionEstablished(WebSocketSession session) throws Exception {
		System.out.println("连接已经创建");
	}

	@Override
	protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
		// 接受服务端的消息
		String echoMessage = this.echoService.getMessage(message.getPayload());

		session.sendMessage(new TextMessage(echoMessage));
	}

	@Override
	public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
		session.close(CloseStatus.SERVER_ERROR);
	}
}
